const { DataTypes } = require('sequelize');
const { sequelize } = require('../utils/sequelize');
const config = require('../config/database');

// 用户第三方认证模型
const UserAuth = sequelize.define(
  'BidUserAuth', // 模型名称
  {
    id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      comment: '主键ID'
    },
    user_id: {
      type: DataTypes.STRING(50),
      allowNull: false,
      comment: '用户ID'
    },
    auth_type: {
      type: DataTypes.STRING(20),
      allowNull: false,
      comment: '认证类型：wechat-微信，qq-QQ，alipay-支付宝，apple-苹果'
    },
    code: {
      type: DataTypes.STRING(64),
      allowNull: true,
      comment: '授权码'
    },
    openid: {
      type: DataTypes.STRING(100),
      allowNull: false,
      comment: '第三方平台用户唯一标识'
    },
    unionid: {
      type: DataTypes.STRING(100),
      allowNull: true,
      comment: '微信unionid（跨应用统一标识）'
    },
    access_token: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '访问令牌'
    },
    refresh_token: {
      type: DataTypes.STRING(500),
      allowNull: true,
      comment: '刷新令牌'
    },
    token_expires_at: {
      type: DataTypes.DATE,
      allowNull: true,
      comment: '令牌过期时间'
    },
    user_info: {
      type: DataTypes.JSON,
      allowNull: true,
      comment: '第三方用户信息（JSON格式存储）'
    },
    status: {
      type: DataTypes.TINYINT,
      defaultValue: 1,
      comment: '状态（1:正常, 0:禁用）'
    }
  },
  {
    tableName: config.mysql.prefix + 'user_auth',
    timestamps: true,
    createdAt: 'created_at',
    updatedAt: 'updated_at',
    indexes: [
      { fields: ['user_id'], name: 'idx_user_id' },
      { fields: ['auth_type', 'openid'], name: 'idx_auth_type_openid' },
      { fields: ['unionid'], name: 'idx_unionid' },
      { fields: ['code'], name: 'idx_code' }
    ],
    comment: '用户第三方认证表'
  }
);

module.exports = UserAuth;